﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using System.IO;
using System.Threading;

/// <summary>
/// Summary description for FileProcess
/// </summary>
public static class FileProcess
{
    /// <summary>
    /// Dùng cho viec upload file từ client đến sever như file text, dzữ liệu đơn giản
    /// </summary>
    /// <param name="localFile"></param>
    /// <param name="uploadUrl"></param>
    static public void UploadFile(string localFile, string uploadUrl)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
        req.Method = "PUT";
        req.AllowWriteStreamBuffering = true;

        // Retrieve request stream and wrap in StreamWriter
        Stream reqStream = req.GetRequestStream();
        StreamWriter wrtr = new StreamWriter(reqStream);

        // Open the local file
        StreamReader rdr = new StreamReader(localFile);

        // loop through the local file reading each line
        //  and writing to the request stream buffer
        string inLine = rdr.ReadLine();
        while (inLine != null)
        {
            wrtr.WriteLine(inLine);
            inLine = rdr.ReadLine();
        }

        rdr.Close();
        wrtr.Close();

        req.GetResponse();
    }
    /// <summary>
    /// Upload File từ client theo dạng binary lên sever như file hình ảnh v.v....
    /// </summary>
    /// <param name="localFile"></param>
    /// <param name="uploadUrl"></param>
    static public void UploadFileBinary(string localFile, string uploadUrl)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);

        req.Method = "PUT";
        req.AllowWriteStreamBuffering = true;

        // Retrieve request stream
        Stream reqStream = req.GetRequestStream();

        // Open the local file
        FileStream rdr = new FileStream(localFile, FileMode.Open);

        // Allocate byte buffer to hold file contents
        byte[] inData = new byte[4096];

        // loop through the local file reading each data block
        //  and writing to the request stream buffer
        int bytesRead = rdr.Read(inData, 0, inData.Length);
        while (bytesRead > 0)
        {
            reqStream.Write(inData, 0, bytesRead);
            bytesRead = rdr.Read(inData, 0, inData.Length);
        }

        rdr.Close();
        reqStream.Close();

        req.GetResponse();
    }
    /// <summary>
    /// download file từ server đến client theo dạng bình thường
    /// </summary>
    /// <param name="localFile"></param>
    /// <param name="downloadUrl"></param>
    static public void DownloadFile(string localFile, string downloadUrl)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(downloadUrl);
        req.Method = "GET";

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        // Retrieve response stream and wrap in StreamReader
        Stream respStream = resp.GetResponseStream();
        StreamReader rdr = new StreamReader(respStream);

        // Create the local file
        StreamWriter wrtr = new StreamWriter(localFile);

        // loop through response stream reading each line
        //  and writing to the local file
        string inLine = rdr.ReadLine();
        while (inLine != null)
        {
            wrtr.WriteLine(inLine);
            inLine = rdr.ReadLine();
        }

        rdr.Close();
        wrtr.Close();
    }
    /// <summary>
    /// download file từ server đến client theo dạng file binary
    /// </summary>
    /// <param name="localFile"></param>
    /// <param name="downloadUrl"></param>
    static public void DownloadFileBinary(string localFile, string downloadUrl)
    {

        downloadUrl = "E:\\BEMS\\BEMS.Web\\Upload\\khode\\";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(downloadUrl);
        req.Method = "GET";

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        // Retrieve response stream
        Stream respStream = resp.GetResponseStream();

        // Create local file
        FileStream wrtr = new FileStream(localFile, FileMode.Create);

        // Allocate byte buffer to hold stream contents
        byte[] inData = new byte[4096];

        // loop through response stream reading each data block
        //  and writing to the local file
        int bytesRead = respStream.Read(inData, 0, inData.Length);
        while (bytesRead > 0)
        {
            wrtr.Write(inData, 0, bytesRead);
            bytesRead = respStream.Read(inData, 0, inData.Length);
        }

        respStream.Close();
        wrtr.Close();
    }
    public static void Download(string sFileName, string sFilePath)
    {
        HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
        String Header = "Attachment; Filename=" + sFileName;
        HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
        System.IO.FileInfo Dfile = new System.IO.FileInfo(sFilePath);
        HttpContext.Current.Response.WriteFile(Dfile.FullName+sFileName);
        HttpContext.Current.Response.End();
    }   
    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                int pack = 10240; //10K bytes
                int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }
}
